package com.jy.app.lib.update;

import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.support.v4.content.FileProvider;
import android.webkit.MimeTypeMap;
import android.widget.Toast;

import com.jy.app.lib.application.BaseApplication;

import java.io.File;
import java.io.IOException;
import java.util.List;

public class DownloadAndInstaller {
    private Context mContext;
    private Uri CONTENT_URI = Uri.parse("content://downloads/my_downloads");
    private DownloadManager manager;
    private DownloadCompleteReceiver receiver;
    private static long id = -1;
    private String url = "";
    private String Path = "";
    private String fileName = "";
    private DownloadManager.Request down;
    private DownloadAppConfig dlapcConfig;
    private DownloadChangeObserver downloadObserver;
    private Handler handler;

    public DownloadAndInstaller(Context context) {
        this.mContext = context;
        dlapcConfig = new DownloadAppConfig(context);
        downloadObserver = new DownloadChangeObserver();
        manager = (DownloadManager) context.getSystemService(context.DOWNLOAD_SERVICE);
        receiver = new DownloadCompleteReceiver();
        Path = "/" + context.getPackageName() + "/Download/";
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public void setHandler(Handler handler) {
        this.handler = handler;
    }

    public long getId() {
        return this.id;
    }

    public void startDownLoad() {
        downLoad();
    }

    public void registerReceiver(long id) {
        if (BaseApplication.mAppContext != null) {
            this.id = id;
            BaseApplication.mAppContext.registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
        }
    }

    private void registerReceiver() {
        if (BaseApplication.mAppContext != null) {
            BaseApplication.mAppContext.registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
            BaseApplication.mAppContext.getContentResolver().registerContentObserver(CONTENT_URI, true,
                    downloadObserver);
        }
    }

    private void unregisterReceiver() {
        if (receiver != null && BaseApplication.mAppContext != null)
            BaseApplication.mAppContext.unregisterReceiver(receiver);
    }

    private String fileName() {
        String str[] = url.split("/");
        return str[str.length - 1];
    }

    private void downLoad() {
        if (fileName.equals("")) {
            fileName = fileName();
        }
        fileIsExists();
        if (id == -1) {
            //创建下载请求
            down = new DownloadManager.Request(Uri.parse(url));
            //设置允许使用的网络类型，这里是移动网络和wifi都可以
            MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
            String mimeString = mimeTypeMap.getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(url));
            down.setMimeType(mimeString);
            down.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE | DownloadManager.Request.NETWORK_WIFI);
            //禁止发出通知，既后台下载
            down.setShowRunningNotification(true);
            //不显示下载界面
            down.setVisibleInDownloadsUi(true);
            //设置下载后文件存放的位置
            down.setDestinationInExternalPublicDir(Path, fileName);
            //将下载请求放入队列
            id = manager.enqueue(down);
            dlapcConfig.setDownLoadId(id);
            dlapcConfig.setDownLoadPathName(Environment.getExternalStorageDirectory().getPath() + Path + fileName);
            registerReceiver();
            //保存id
        } else {
            if (mContext != null)
                Toast.makeText(mContext, "已经开始下载了！", Toast.LENGTH_SHORT).show();
        }
    }

    //接受下载完成后的intent
    class DownloadCompleteReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction().equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE)) {
                if (id == intent.getLongExtra(DownloadManager.EXTRA_DOWNLOAD_ID, -1)) {
                    File file;
                    if (fileName == null) {
                        file = new File(dlapcConfig.getDownLoadPathName());
                    } else {
                        file = new File(Environment.getExternalStorageDirectory().getPath() + Path + fileName);
                    }
                    installApk(file);
                    id = -1;
                }
            }
        }
    }

    public void setStopDown() {
        manager.remove(id);
        id = -1;
        dlapcConfig.setDownLoadId(id);
        id = -1;
        stopService();
    }

    class DownloadChangeObserver extends ContentObserver {


        public DownloadChangeObserver() {
            super(handler);
        }


        @Override
        public void onChange(boolean selfChange) {
            updateView();
        }

    }

    private void updateView() {
        int bytesAndStatus = getBytesAndStatus(id);
        handler.sendEmptyMessage(bytesAndStatus == 100 ? 99 : bytesAndStatus);
    }

    public int getBytesAndStatus(long downloadId) {
        int bytesAndStatus = 0;
        DownloadManager.Query query = new DownloadManager.Query().setFilterById(downloadId);
        Cursor c = null;
        try {
            c = manager.query(query);
            if (c != null && c.moveToFirst()) {
                float a = c.getInt(c.getColumnIndexOrThrow(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR));
                float b = c.getInt(c.getColumnIndexOrThrow(DownloadManager.COLUMN_TOTAL_SIZE_BYTES));
//                bytesAndStatus[2] = c.getInt(c.getColumnIndex(DownloadManager.COLUMN_STATUS));
                float d = a / b;
                bytesAndStatus = (int) (d * 100);
            }
        } finally {
            if (c != null) {
                c.close();
            }
        }
        return bytesAndStatus;
    }

    public void stopService() {
        if (mContext != null) {
            mContext.stopService(new Intent(mContext, UpDateAppService.class));
            mContext.getContentResolver().registerContentObserver(CONTENT_URI, true, downloadObserver);
            mContext = null;
        }

    }

    private void installApk(File updateFile) {
        try {
            String[] command = {"chmod", "777", updateFile.getPath()};
            ProcessBuilder builder = new ProcessBuilder(command);
            builder.start();
        } catch (IOException e) {
        }
        if (BaseApplication.mAppContext != null) {
            try{
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                Uri apkUri;
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    apkUri = FileProvider.getUriForFile(mContext, mContext.getPackageName()+".provider", updateFile);
                    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                } else {
                    apkUri = Uri.fromFile(updateFile);
                }
                intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
                // 查询所有符合 intent 跳转目标应用类型的应用，注意此方法必须放置在 setDataAndType 方法之后
                List<ResolveInfo> resolveLists = mContext.getPackageManager().queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
                // 然后全部授权
                for (ResolveInfo resolveInfo : resolveLists){
                    String packageName = resolveInfo.activityInfo.packageName;
                    mContext.grantUriPermission(packageName, apkUri, Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                }
                mContext.startActivity(intent);
            }catch (Exception e){
                e.printStackTrace();
            }
            dlapcConfig.setDownLoadId(-1);
            stopService();
            unregisterReceiver();
            handler.sendEmptyMessage(100);
            if (UpdateManager.mHander != null) {
                UpdateManager.mHander.sendEmptyMessage(UpdateManager.CHECK_UPDATE_IS_CLICK);
            }
        }
    }

    private boolean fileIsExists() {
        File file;
        try {
            file = new File(Environment.getExternalStorageDirectory().getPath() + Path);
            if (!file.exists()) {
                file.mkdirs();
                return false;
            }

        } catch (Exception e) {
            return false;
        }
        file = new File(Environment.getExternalStorageDirectory().getPath() + Path + fileName);
        file.delete();
        return true;
    }
}
